import os

import pytest
from base.base_page import BasePage
from common.yaml_util import send_message_to_feishu


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''用例断言失败时，自动截图'''
    outcome = yield
    rep = outcome.get_result()
    if rep.when == 'call' and rep.failed:
        mode = 'a' if hasattr(rep, 'wasxfail') else 'w'
        if mode == 'w':
            if hasattr(item.instance, 'driver'):
                # print(f"Taking screenshot for {item.originalname}")
                BasePage(driver=item.instance.driver).savee_screenshot(page_name=f'{item.originalname}断言错误')
            else:
                print("Driver not found on test instance")



def pytest_addoption(parser):
    parser.addoption("--no-allure", action="store_true", default=False, help="Disable Allure report")

def pytest_configure(config):
    '''no-allure 参数控制是否生成 Allure 报告，在更目录下生成'''
    # 获取当前工作目录
    current_dir = os.getcwd()
    # 检查是否传递了 --no-allure 参数
    if config.getoption("--no-allure"):
        config.option.allure_report_dir = None
    else:
        # 根据当前目录决定是否生成 Allure 报告
        if 'case' in current_dir:
            config.option.allure_report_dir = None
        else:
            config.option.allure_report_dir = 'reports/temp'
        # pytest - -no - allure 不生成报告


import time
def pytest_terminal_summary(terminalreporter):
    """
    钩子函数手机测试报告信息，通过封装的方法发送到飞书、也可邮件、钉钉的，演示的是飞书
    """
    print(terminalreporter.stats)
    collected=( terminalreporter._numcollected)
    passed=(len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown']))
    failed=(len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']))
    error=(len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown']))
    skipped=( len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown']))
    if terminalreporter._numcollected == 0:
        sounce='0.00%'
    else:
        sounce=('%.2f' % (len(terminalreporter.stats.get('passed', [])) / terminalreporter._numcollected * 100) + '%')
    # terminalreporter._sessionstarttime 会话开始时间
    duration =float(f'{(time.time() - terminalreporter._sessionstarttime):.2f}')
    mine =f'{int(duration)//60}分钟{(int(duration) % 60)}秒'
    send_message_to_feishu(collected, passed, failed,  skipped,error, sounce, mine)
